import axios from 'axios';

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response.data;
  }

  throw new Error('提交错误，请检查');
}

function checkState(data) {
  if (data.state === 'success') {
    return data;
  }

  throw new Error('提交错误，请检查');
}

export const Get = (url, params, headers = {}) => {
  return axios
    .get(url, { params, headers })
    .then((response) => checkStatus(response))
    .then((data) => checkState(data));
};

export const Post = (url, body, headers = {}) => {
  return axios
    .post(url, body, { headers })
    .then((response) => checkStatus(response))
    .then((data) => checkState(data));
};

export const Put = (url, body, headers = {}) => {
  return axios
    .put(url, body, { headers })
    .then((response) => checkStatus(response))
    .then((data) => checkState(data));
};
